//
//  searchPageViewController.m
//  SearchControllerTestDemo
//
//  Created by apple on 2017/9/7.
//  Copyright © 2017年 apple. All rights reserved.
//

#define Start_X 45.f                                   // 第一个按钮的X坐标
#define Start_Y 60.f                                   // 第一个按钮的Y坐标
#define Width_Space  45.f                              // 2个按钮之间的横间距
#define Height_Space 35.f                              // 竖间距
#define Button_Height 96.f                             // 循环按钮的高
#define Button_Width  300.f                            // 循环按钮的宽
#define Button_Radius 5.f                              // 按钮圆角
#define ImageView_Title_Width 50.f                     //标题图片的大小

#import <QuartzCore/QuartzCore.h>
#import "searchPageViewController.h"
#import "lastSearchTableViewCell.h"
#import "UINavigationBar+Awesome.h"
#import "ECSearchPageModel.h"
#import "ECUIVC_SearchResultList.h"
#import "ECUITextField_Search.h"
#import "ECListArrayOfHistory.h"

@interface searchPageViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,lastSearchTableViewCellDelegate>{
    
    //最近搜索view
    UIView *titleOfLastSearchView;
}

///搜索view
@property(nonatomic,strong)ECUITextField_Search *searchView;
///搜索按钮
@property (nonatomic, strong) ECUButton *searchBtn;

@property (nonatomic, strong) UIView *hotRecommendView;

@property (nonatomic, strong) UITableView *lastSearchTableview;
//搜索历史记录数组
@property (nonatomic, strong) NSMutableArray *lastSearchArray;
///推荐课程列表
@property (nonatomic, strong) NSMutableArray *recommendCourseList;

@end

@implementation searchPageViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor whiteColor]];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar addSubview:self.searchView];
    self.lastSearchArray = [ECListArrayOfHistory getListArrayOfHistory];
    [self.lastSearchTableview reloadData];
    DLog(@"%@",self.lastSearchArray);
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    // add yy
    [self.searchView removeFromSuperview];
  
}

-(void)viewDidLoad{
    [super viewDidLoad];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@""style:UIBarButtonItemStylePlain target:self action:nil];
    [self getDataWithURL];
}


- (ECUITextField_Search *)searchView
{
    if (!_searchView) {
        WeakSelf(weakSelf);
        _searchView = [[ECUITextField_Search alloc]initWithFrame:CGRectMake(40, 5, kProportion_Width(780) + 60, 35)];
        _searchView.block_search = ^(id obj) {
            [weakSelf searchBtnTouched:obj];
        };
    }
    return _searchView;
}

- (void)setNavigationLeftBar{
    ECUButton *button = [[ECUButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [button setImage:[UIImage imageNamed:@"Mine_back"] forState:0];
    // 让按钮内部的所有内容左对齐
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    // 修改导航栏左边的item
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}
#pragma mark - 返回点击事件
- (void)back{
    [self.searchView removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)getDataWithURL{
    DLog(@"%@",[[UserInfoManager shareUser] token]);
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HWHttpTool requestWithMethod:@"GET"
                              url:URL_GET_HotSearch
                           params:nil
                          headers:nil
                          success:^(id json) {
                              DLog(@"%@",json);
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                              [self.recommendCourseList addObjectsFromArray: [ECSearchPageModel mj_objectArrayWithKeyValuesArray:json[@"data"]]];
                              if (self.recommendCourseList.count != 0) {
                                  [self createHotRecommendListView];
                              }
                              
                              [self createLastSearchTableview];
                          }
                          failure:^(NSError *error) {
                              DLog(@"%@",error);
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                          }];
}

//热门搜索视图
-(UIView *)createHotRecommendListView{
    if (!_hotRecommendView) {
        
        //热门搜索view
        UIView *titleOfHotSearchView = [[UIView alloc]init];
        [self.view addSubview:titleOfHotSearchView];
        [titleOfHotSearchView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_offset(0);
            make.top.mas_equalTo(@(kProportion_Height(Start_Y)));
            make.height.mas_offset(25);
        }];
        
        UIImageView *titleOfHotSearchView_imageview = [[UIImageView alloc]init];
        [titleOfHotSearchView addSubview:titleOfHotSearchView_imageview];
        titleOfHotSearchView_imageview.image = [UIImage imageNamed:@"CourseList_search_hotSearchImage"];
        [titleOfHotSearchView_imageview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(kProportion_Width(Start_X));
            make.centerY.mas_equalTo(titleOfHotSearchView.mas_centerY);
            make.height.width.mas_offset(kProportion_Width(ImageView_Title_Width));
        }];
        
        UILabel *titleOfHotSearchView_titleLab = [[UILabel alloc]init];
        [titleOfHotSearchView addSubview:titleOfHotSearchView_titleLab];
        titleOfHotSearchView_titleLab.text = @"热门搜索";
        titleOfHotSearchView_titleLab.textColor =[UIColor colorWithHexString:@"#b3b3b3"];
        [titleOfHotSearchView_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(titleOfHotSearchView_imageview.mas_right).offset(10);
            make.width.mas_offset(100);
            make.centerY.mas_equalTo(titleOfHotSearchView.mas_centerY);
        }];
        
        _hotRecommendView = [[UIView alloc]init];
        _hotRecommendView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_hotRecommendView];
        
        //循环创建按钮
        for (int i = 0; i < self.recommendCourseList.count; i++) {
            NSInteger index = i % 3;
            NSInteger row = i/3;//行
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.backgroundColor = [UIColor colorWithRed:0.97f green:0.98f blue:0.97f alpha:1.00f];
            btn.frame = CGRectMake(index * (kProportion_Width(Button_Width + Width_Space)) + kProportion_Width(Start_X),
                                   row*(kProportion_Height(Button_Height + Height_Space)),
                                   kProportion_Width(Button_Width),
                                   kProportion_Height(Button_Height));
            ECSearchPageModel *model = self.recommendCourseList[i];
            [btn setTitle:model.name forState:0];
            btn.layer.masksToBounds = YES;
            btn.layer.cornerRadius = Button_Radius;
            [btn setTitleColor:[UIColor colorWithRed:0.36f green:0.37f blue:0.37f alpha:1.00f] forState:0];
            btn.titleLabel.font = [UIFont systemFontOfSize:15.f];
            btn.tag = 10 + i;//根据tag标识
            [btn addTarget:self action:@selector(hotSearchBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [_hotRecommendView addSubview:btn];
        }
        
        [self.hotRecommendView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(titleOfHotSearchView.mas_bottom).mas_offset(kProportion_Height(Start_Y));
            make.left.right.mas_equalTo(0);
            
            NSInteger row;//确定行数
            if (self.recommendCourseList.count%3 == 0) {
                row = self.recommendCourseList.count/3;
            }else{
                row = self.recommendCourseList.count/3 + 1;
            }
            make.height.offset((row) * kProportion_Height(Button_Height+Height_Space));
        }];
        
    }
    //必要时更新约束
    [self.view updateConstraintsIfNeeded];
    return _hotRecommendView;
}

-(UITableView *)createLastSearchTableview{
    if (!_lastSearchTableview) {
        
        
        //最近搜索view
        titleOfLastSearchView = [[UIView alloc]init];
        [self.view addSubview:titleOfLastSearchView];
        [titleOfLastSearchView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_offset(0);
            if (self.recommendCourseList.count == 0) {
                make.top.mas_equalTo(0).mas_offset(kProportion_Height(35));
            }else{
                make.top.mas_equalTo(self.hotRecommendView.mas_bottom).mas_offset(kProportion_Height(35));
            }
            make.height.mas_offset(25);
        }];
        
        UIImageView *titleOfLastSearchView_imageview = [[UIImageView alloc]init];
        [titleOfLastSearchView addSubview:titleOfLastSearchView_imageview];
        titleOfLastSearchView_imageview.image = [UIImage imageNamed:@"CourseList_search_lastSearchImage"];
        [titleOfLastSearchView_imageview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(kProportion_Width(Start_X));
            make.centerY.mas_equalTo(titleOfLastSearchView.mas_centerY);
            make.height.width.mas_offset(kProportion_Width(ImageView_Title_Width));
        }];
        
        UILabel *titleOfLastSearchView_titleLab = [[UILabel alloc]init];
        [titleOfLastSearchView addSubview:titleOfLastSearchView_titleLab];
        titleOfLastSearchView_titleLab.text = @"最近搜索";
        titleOfLastSearchView_titleLab.textColor = [UIColor colorWithHexString:@"#b3b3b3"];
        [titleOfLastSearchView_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(titleOfLastSearchView_imageview.mas_right).offset(10);
            make.width.mas_offset(100);
            make.centerY.mas_equalTo(titleOfLastSearchView.mas_centerY);
        }];
        
        _lastSearchTableview = [[UITableView alloc]init];
        [self.view addSubview:self.lastSearchTableview];
        _lastSearchTableview.delegate = self;
        _lastSearchTableview.dataSource = self;
        _lastSearchTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _lastSearchTableview.scrollEnabled = NO;
        [self.lastSearchTableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.mas_equalTo(titleOfLastSearchView.mas_bottom).mas_offset(kProportion_Height(Start_Y));
            make.bottom.mas_equalTo(0);
        }];
    }
    return _lastSearchTableview;
}

#pragma mark tableview delegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return (self.lastSearchArray.count - 1)/2 + 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identify = @"lastSearchTableViewCell";
    lastSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (!cell) {
        cell = [[lastSearchTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
        cell.delegate = self;
    }
    
    NSUInteger row = indexPath.row;
    for (NSInteger i = 0; i < 2; i++) {//循环2列
        if (row * 2 + i > self.lastSearchArray.count - 1) {//预防出错
            break;
        }
        //赋值语句
        [cell setContentOfCellWithModel:self.lastSearchArray[row * 2 + i] andIndex:row * 2 + i];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44.f;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    tableView.tableFooterView = footView;
    
    UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [footView addSubview:delBtn];
    [delBtn setTitle:@"清除历史记录" forState:0];
    [delBtn setTitleColor:[UIColor colorWithRed:0.19f green:0.62f blue:0.97f alpha:1.00f] forState:0];
    delBtn.titleLabel.font = [UIFont systemFontOfSize:15.f];
    [delBtn addTarget:self action:@selector(delBtnClcik) forControlEvents:UIControlEventTouchUpInside];
    [delBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(footView);
        make.height.mas_offset(20);
        make.width.mas_offset(100);
    }];
    
    //根据数组个数 判断是否显示删除按钮
    if (self.lastSearchArray.count > 0) {
        [delBtn setHidden:NO];
    }else{
        [delBtn setHidden:YES];
    }
    
    return footView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40;
}

#pragma mark btnClcik

/*
 热门搜索按钮点击事件
 */
-(void)hotSearchBtnClick:(UIButton *)btn{
    ECSearchPageModel *model = self.recommendCourseList[btn.tag - 10];
    NSString *str = model.name;
    DLog(@"%@",str);
    [ECListArrayOfHistory addListArrayOfHistoryWith:str];
    [self showSearchListResultWithCourseName:str];
    
}
-(void) showSearchListResultWithCourseName:(NSString *)name
{
    ECUIVC_SearchResultList *uivc_searchList = [[ECUIVC_SearchResultList alloc]init];
    uivc_searchList.searchName = name;
    [self.navigationController pushViewController:uivc_searchList animated:YES];
}
/*
 搜索框点击事件
 */
- (void)searchBtnTouched:(id)obj{
    DLog(@"点击搜索");
    if ([(NSString *)obj isEqualToString:@""]) {
        return;
    }
    //获取搜索内容；
    NSString *str = (NSString *)obj;
    DLog(@"%@",str);
    [ECListArrayOfHistory addListArrayOfHistoryWith:str];
    
#warning  处理其他操作....
    [self showSearchListResultWithCourseName:str];
}

#pragma  mark  delegateOfCell
/*
 最近搜索点击事件
 */
-(void)delegateOfTitleBtnClickOfWitch:(NSInteger)index{
    DLog(@"%@",self.lastSearchArray[index]);
    [self showSearchListResultWithCourseName:self.lastSearchArray[index]];
    
    [ECListArrayOfHistory deleteListArrayOfHistoryOfIndex:index];
    [ECListArrayOfHistory addListArrayOfHistoryWith:self.lastSearchArray[index]];
}

-(void)delegateOfDelBtnClickOfWitch:(NSInteger)index{
    [ECListArrayOfHistory deleteListArrayOfHistoryOfIndex:index];
    [self.lastSearchArray removeObjectAtIndex:index];
    [self.lastSearchTableview reloadData];
}

-(void)delBtnClcik{
    NSLog(@"删除历史数据");
    [self.lastSearchArray removeAllObjects];
    [self.lastSearchTableview reloadData];
    [ECListArrayOfHistory clearListArrayOfHistory];
}

/*
 懒加载
 */
-(NSMutableArray *)recommendCourseList{
    if (!_recommendCourseList) {
        _recommendCourseList = [[NSMutableArray alloc]init];
    }
    return _recommendCourseList;
}

-(NSMutableArray *)lastSearchArray{
    if (!_lastSearchArray) {
        _lastSearchArray = [[NSMutableArray alloc]init];
    }
    return _lastSearchArray;
}

@end
